package net.piggy.core.socket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import net.piggy.core.session.dubbo.DubboGatewaySessionFactory;
import net.piggy.core.util.GatewayConfigUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.Callable;

public class GatewaySocketServer implements Callable<Channel> {
    private final Logger logger = LoggerFactory.getLogger(GatewaySocketServer.class);
    private final DubboGatewaySessionFactory gatewaySessionFactory;
    private Channel channel;

    public GatewaySocketServer(DubboGatewaySessionFactory gatewaySessionFactory) {
        this.gatewaySessionFactory = gatewaySessionFactory;

    }

    @Override
    public Channel call() {
        EventLoopGroup boss = new NioEventLoopGroup(1);
        EventLoopGroup work = new NioEventLoopGroup(4);
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(boss, work).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128)
                .childHandler(new GatewayChannelInitializer(gatewaySessionFactory));
        ChannelFuture channelFuture = bootstrap.bind(GatewayConfigUtil.getGatewayConfig().getPort()).syncUninterruptibly();
        return channelFuture.channel();
    }

}